<?php

/**
 * This is the model class for table "trade_productcategory".
 *
 * The followings are the available columns in table 'trade_productcategory':
 * @property string $productCategoryId
 * @property string $name
 * @property string $description
 * @property string $parentId
 * @property integer $status
 * @property string $iconUrl
 * @property integer $level
 * @property string $createdUserId
 * @property string $createdDate
 * @property string $updatedUserId
 * @property string $updatedDate
 * @property integer $isDeleted
 *
 * The followings are the available model relations:
 * @property Product[] $products
 * @property HrmUser $createdUser
 * @property HrmUser $updatedUser
 * @property ProductCategory $parent
 * @property ProductCategory[] $productcategories
 */
class ProductCategory extends BaseDateUserModel
{
        public $file_upload;
        
        const ROOT = Constant::ROOT_NAME_CATEGORY ;
	/**
	 * Returns the static model of the specified AR class.
	 * @return ProductCategory the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'pjm_book_category';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('name', 'required'),
                        array('file_upload', 'file', 'types'=>'jpg, gif, png', 'allowEmpty' => true),
			array('status, level, isDeleted', 'numerical', 'integerOnly'=>true),
			array('name, description, iconUrl', 'length', 'max'=>255),
			array('parentId, createdUserId, updatedUserId', 'length', 'max'=>20),
			array('createdDate, updatedDate', 'safe'),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('productCategoryId, name, description, parentId, status, iconUrl, level, createdUserId, createdDate, updatedUserId, updatedDate, isDeleted', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
//			'products' => array(self::HAS_MANY, 'Product', 'productCategoryId'),
//			'createdUser' => array(self::BELONGS_TO, 'User', 'createdUserId'),
//			'updatedUser' => array(self::BELONGS_TO, 'User', 'updatedUserId'),
//			'parent' => array(self::BELONGS_TO, 'ProductCategory', 'parentId'),
//			'productcategories' => array(self::HAS_MANY, 'ProductCategory', 'parentId'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'productCategoryId' => 'ID',
			'name' => 'Name',
			'description' => 'Description',
			'parentId' => 'Parent',
			'status' => 'Status',
			'iconUrl' => 'Icon Url',
			'level' => 'Level',
			'createdUserId' => 'Created User',
			'createdDate' => 'Created Date',
			'updatedUserId' => 'Updated User',
			'updatedDate' => 'Updated Date',
			'isDeleted' => 'Is Deleted',
                        'file_upload' => 'Representative Image',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('productCategoryId',$this->productCategoryId,true);
		$criteria->compare('name',$this->name,true);
		$criteria->compare('description',$this->description,true);
		$criteria->compare('parentId',$this->parentId,true);
		$criteria->compare('status',$this->status);
		$criteria->compare('iconUrl',$this->iconUrl,true);
		$criteria->compare('level',$this->level);
		$criteria->compare('createdUserId',$this->createdUserId,true);
		$criteria->compare('createdDate',$this->createdDate,true);
		$criteria->compare('updatedUserId',$this->updatedUserId,true);
		$criteria->compare('updatedDate',$this->updatedDate,true);
		$criteria->compare('isDeleted',$this->isDeleted);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}
        
	public function searchIsTrashed($isTrashed)
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('productCategoryId',$this->productCategoryId,true);
		$criteria->compare('name',$this->name,true);
		$criteria->compare('description',$this->description,true);
		$criteria->compare('parentId',$this->parentId,true);
		$criteria->compare('status',$this->status);
		$criteria->compare('iconUrl',$this->iconUrl,true);
		$criteria->compare('level',$this->level);
		$criteria->compare('createdUserId',$this->createdUserId,true);
		$criteria->compare('createdDate',$this->createdDate,true);
		$criteria->compare('updatedUserId',$this->updatedUserId,true);
		$criteria->compare('updatedDate',$this->updatedDate,true);
		$criteria->compare('isDeleted',$isTrashed);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}
        
        //provide list of categories with original root 
        //Ex: ROOT -> Computer -> Dell
        public static function getAllParentCategoriesTracking(){
            $listCat = CHtml::listData(ProductCategory::model()->findAll(), "productCategoryId", "name");
            $allCat = array();
            $allCat[] = self::ROOT ;
            
            foreach ($listCat as $key => $value){        
                $allCat[$key] = self::trackCategoryFromRoot( $key) . self::getCatNameById($key);
            }
            
            asort($allCat);
            
            return $allCat;
        }
        
        //append previous category to current one
        public static function trackCategoryFromRoot($catId){
            //$str = $this->getCatNameById($catId);
            $str = "";
            
            //find model which has that id
            $cat = ProductCategory::model()->findByAttributes(array("productCategoryId"=>$catId));
            
            //if comes to root then stop
            if (count($cat) == 0)
                return "";
            
            //append parent name to string
            if ($cat->parentId == 0){
                $str = self::ROOT . " -> " ;
                return $str;
            }
            else
                $str =  self::getCatNameById($cat->parentId) . " -> "  ;
                
                //recursive call
                $str = self::trackCategoryFromRoot($cat->parentId)  . $str;
            
            return $str;
        }
        
        //get Category name according to its id
        public static function getCatNameById($catid){
            $criteria = new CDbCriteria;
            $criteria->select = 'name';
            $criteria->condition = 'productCategoryId =:x';
            $criteria->params = array(':x'=>$catid);
            $criteria->limit = 1;
            
            $result = ProductCategory::model()->find($criteria);
            if ( count($result) == 0)
                return self::ROOT;
            else
                return $result->name;
        }
        
        //get all categories 
        public static function getAllCategories(){
            $allCat = CHtml::listData(ProductCategory::model()->findAll(), "productCategoryId", "name");
            return $allCat;
        }
        
        
        public function beforeSave(){
            if (parent::beforeSave()) {
                //autoset level for category
                $categoryFromRoot = ProductCategory::trackCategoryFromRoot($this->parentId);
                if (strcmp($categoryFromRoot, "") != 0) { // when parent != root
                    $levelCount = explode($categoryFromRoot, " -> ");
                    $this->level = count($levelCount) + 1;
                }
                else // when parent = root
                    $this->level = 1;
                
                return true;
            }
            return false;
        }
        
        public function getAllProductsAssociated(){
            $allProductsAssociated = Product::model()->findAllByAttributes(array('productCategoryId' => $this->productCategoryId));
            return $allProductsAssociated;
        }
}